﻿#include <stdio.h>
#include <curl/curl.h>
#include <string>

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
	((std::string*)userdata)->append(ptr, nmemb);
	return nmemb;
}

int main11111(int argc, void* argv)
{
	curl_global_init(CURL_GLOBAL_DEFAULT);
	CURL* curl = curl_easy_init();
	if (curl)
	{
		// set url
		curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:9091/hfdrcall/test/http");

		// no certificate, not verify server certificate
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);

		// set http method
		curl_easy_setopt(curl, CURLOPT_POST, 1);

		// set header
		struct curl_slist * slist = nullptr;
		slist = curl_slist_append(slist, "Content-Type : application/json");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

		// set body
		std::string body = "{\
            \"title\":\"libcurl post title 这是标题\",\
            \"body\" : \"libcurl post body\",\
            \"userId\" : 1}";
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());

		// set response callback to read response
		std::string response_data;
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_data);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
		CURLcode res = curl_easy_perform(curl);
		if (res != CURLE_OK)
		{
			fprintf(stderr, "curl_easy_perform() failed: %s\n",
				curl_easy_strerror(res));
		}
		else
		{
			// get response code
			/*long response_code;
			curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
			printf("response code %d \n", response_code);*/
			printf("response data : \n ");
			printf(response_data.c_str());
		}

		curl_slist_free_all(slist);
		curl_easy_cleanup(curl);
	}

	curl_global_cleanup();
	return 0;
}